package com.umeox.watch.moto.settings;


import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Rect;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.telephony.SubscriptionManager;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.umeox.moto.common.log.LogUtils;
import com.umeox.moto.common.utils.AppUtils;
import com.umeox.moto.watch.themes.app.ThemeAppCompatActivity;
import com.umeox.watch.moto.settings.ui.CommonSwitchActivity;
import com.umeox.watch.moto.settings.ui.DeviceInfoActivity;
import com.umeox.watch.moto.settings.ui.LanguageActivity;
import com.umeox.watch.moto.settings.ui.UnitActivity;
import com.umeox.watch.moto.settings.ui.VolteSettingActivity;
import com.umeox.watch.moto.settings.utils.CommonUtils;
import com.umeox.watch.moto.settings.utils.RsUiStage;
import com.umeox.watch.moto.settings.view.CustomScrollView;
import com.umeox.watch.moto.settings.view.SettingsItem;


public class SettingsActivity extends ThemeAppCompatActivity implements View.OnClickListener, CustomScrollView.ScrollChangedListener {

    private static final String TAG = SettingsActivity.class.getSimpleName();
    public static final String EXTRA_WIFI_STATUS = "wifi_status";
    public static final int FLAG_RECEIVER_INCLUDE_BACKGROUND = 0x01000000;
    private static final Uri CONTENT_URI = Uri.parse("content://com.redstone.contentProvider/updateState");
    public static final String APN_SETTINGS_ACTIVITY = "com.android.settings.Settings$ApnSettingsActivity";

    private SettingsItem mWifiLl;
    private SettingsItem mTimeLl;
    private SettingsItem mLanguageLl;
    private LinearLayout mUnitsLl;
    private SettingsItem mOTALl;
    private SettingsItem mApnLl;
    private SettingsItem mDeviceImeiLl;
    private SettingsItem mPowerOffLl;

    private TextView mDataTv;
    private CustomScrollView mScrollView;

    private BluetoothAdapter mBluetoothAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_main);
        initView();
        initListener();
    }

    private void initView() {
        mWifiLl = findViewById(R.id.wifi_ll);
        findViewById(R.id.rl_bluetooth).setOnClickListener(this);
        findViewById(R.id.rl_handoff).setOnClickListener(this);
        findViewById(R.id.rl_overlay_screen).setOnClickListener(this);

        mScrollView = findViewById(R.id.sv_qs);
        mScrollView.setScrollChangedListener(this);
        findViewById(R.id.rl_data).setOnClickListener(this);


        mTimeLl = findViewById(R.id.time_ll);
        mLanguageLl = findViewById(R.id.language_ll);
        mUnitsLl = findViewById(R.id.units_ll);
        mOTALl = findViewById(R.id.ota_ll);
        mPowerOffLl = findViewById(R.id.power_off_ll);


        mApnLl = findViewById(R.id.apn_ll);
        mDeviceImeiLl = findViewById(R.id.device_id_ll);

        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        final View voLTEView = findViewById(R.id.rl_volte);
        voLTEView.setOnClickListener(this);

        if (!CommonUtils.hasIccCard(this)) {
            mApnLl.setVisibility(View.GONE);
            voLTEView.setVisibility(View.GONE);
        } else {
            mApnLl.setVisibility(View.VISIBLE);
        }
    }

    private void initListener() {
        mWifiLl.setOnClickListener(this);
        mTimeLl.setOnClickListener(this);
        mLanguageLl.setOnClickListener(this);
        mUnitsLl.setOnClickListener(this);
        mOTALl.setOnClickListener(this);
        mApnLl.setOnClickListener(this);
        mDeviceImeiLl.setOnClickListener(this);
        mPowerOffLl.setOnClickListener(this);
    }

    private void enableBluetoothAdapter(boolean checked) {
        if (checked) {
            mBluetoothAdapter.enable();
        } else {
            mBluetoothAdapter.disable();

        }
    }

    @Override
    protected void onResume() {
        super.onResume();
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.wifi_ll:
                startSettingsActivity("com.umeox.s21wifi", "com.umeox.s21wifi.wifi.WiFiSettingActivity");
                break;
            case R.id.rl_data:
                startSwitchAct(0);
                break;
            case R.id.rl_bluetooth:
                startSettingsActivity("com.umeox.s21wifi", "com.umeox.s21wifi.bluetooth.BluetoothSettingActivity");
                break;
            case R.id.rl_volte:
                startActivity(new Intent(this, VolteSettingActivity.class));
                break;
            case R.id.rl_handoff:
                startSwitchAct(2);
                break;
            case R.id.rl_overlay_screen:
                startSwitchAct(3);
                break;
            case R.id.device_id_ll:
                startActivity(new Intent(SettingsActivity.this, DeviceInfoActivity.class));
                break;
            case R.id.time_ll:
                startSettingsActivity("com.android.settings", "com.android.settings.Settings$DateTimeSettingsActivity");
                break;
            case R.id.language_ll:
                Intent intent = new Intent(SettingsActivity.this, LanguageActivity.class);
                startActivity(intent);
                break;
            case R.id.units_ll:
                startActivity(new Intent(SettingsActivity.this, UnitActivity.class));
                break;
            case R.id.ota_ll:
                if (AppUtils.isApkExist(SettingsActivity.this, "com.umeox.ota")) {
                    startSettingsActivity("com.umeox.ota", "com.umeox.ota.ui.activity.HomeActivity");
                } else {
                    Toast.makeText(SettingsActivity.this, "Can not found OTA Application", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.apn_ll:
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    int subId = getSubId();
                    if (subId != SubscriptionManager.INVALID_SUBSCRIPTION_ID) {
                        Intent apnIntent = new Intent();
                        apnIntent.setClassName("com.android.settings", APN_SETTINGS_ACTIVITY);
                        apnIntent.putExtra("sub_id", subId);
                        startActivity(apnIntent);
                    }
                } else {
                    startSettingsActivity("com.android.settings", "com.android.settings.ApnSettings");
                }
                break;
            case R.id.power_off_ll:
//                Intent powerOffIntent = new Intent();
//                powerOffIntent.setAction("android.intent.action.POWEROFF_DIALOG");
//                powerOffIntent.setPackage("com.umeox.watch.moto.poweroff");
//                powerOffIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES | Intent.FLAG_RECEIVER_FOREGROUND | FLAG_RECEIVER_INCLUDE_BACKGROUND);
//                sendBroadcast(powerOffIntent);

                Intent powerOffIntent = new Intent();
                powerOffIntent.setClassName("com.umeox.watch.moto.poweroff", "com.umeox.watch.moto.poweroff.MainActivity");
                startActivity(powerOffIntent);
                break;
        }
    }

    private void startSwitchAct(int type) {
        Intent startIntent = new Intent(SettingsActivity.this, CommonSwitchActivity.class);
        startIntent.putExtra("type", type);
        startActivity(startIntent);
    }

    private void startSettingsActivity(@NonNull String packageName, @NonNull String className) {
        Intent chooseWifiIntent = new Intent();
        chooseWifiIntent.setClassName(packageName, className);
        startActivity(chooseWifiIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        onScrollChanged(0, 0, 0, 0);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }


    @Override
    public void onScrollChanged(int l, int t, int oldl, int oldt) {
        Rect scrollRect = new Rect();
        mScrollView.getHitRect(scrollRect);
    }

    // 监听URI数据库结果
    private class FOTAObserver extends ContentObserver {

        public FOTAObserver(Handler handler) {
            super(handler);
        }

        // 当ContentProvier数据发生改变，则触发该函数
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            LogUtils.i(TAG, "FOTA状态发生改变");
            int state = queryFOTAState();
            switch (state) {
                case RsUiStage.RS_UI_STAGE_CHECK_END:
//                    mVersionTv.setText("New");
                    break;
                case RsUiStage.RS_UI_STAGE_DOWNLOAD:
//                    mVersionTv.setText("Downloading");
                    break;
                case RsUiStage.RS_UI_STAGE_DOWNLOAD_END:
//                    mVersionTv.setText("Installable");
                    break;
                case RsUiStage.RS_UI_STAGE_CHECK:
                case RsUiStage.RS_UI_STAGE_IDLE:
                case RsUiStage.RS_UI_STAGE_INSTALL:
                default:
//                    mVersionTv.setText(Build.DISPLAY);
                    break;
            }

        }
    }


    /**
     * check new update Data
     **/
    private int queryFOTAState() {
        String[] projection = {"_id", "numb"};
        Cursor cursor = null;
        cursor = getContentResolver().query(CONTENT_URI, projection, "_id = '1'", null, null);

        if (cursor == null) {
            cursor.close();
            Log.d("tstest", "system update cursor == null");

            return RsUiStage.RS_UI_STAGE_IDLE;
        } else {
            if (!cursor.moveToFirst()) {
                return RsUiStage.RS_UI_STAGE_IDLE;
            }
            int number = cursor.getInt(cursor.getColumnIndex("numb"));
            Log.d("tstest", "system update number = " + number);

            cursor.close();
            return number;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private int getSubId() {
        int subid = -1;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            subid = SubscriptionManager.getDefaultDataSubscriptionId();
        }
        Log.d("@M_" + TAG, "GetSimIdBySlot: sub id = " + subid);
        return subid;
    }
}